#!/usr/bin/env python

import optparse
import sys

import numpy
import tables

from charmicat import BadCommandLineError


def main():
    '''
    ptcolumn_print.py [opts] file.h5

    Print a sample of values from each column of a table contained in `file.h5'
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    op.add_option("-c", "--column", dest='cols', action='append', default=[],
                  help='Print only values from column NAME', metavar='NAME')
    op.add_option("-r", "--range", dest='range', nargs=2, type='int', default=None,
                  help='Print values from index LOW to index HIGH, rather than randomly sampling',
                  metavar='LOW HIGH')
    op.add_option("-s", "--sample-size", type='int', dest='sample_size', default=50,
                  help='Read and print a sample of N values from each column',
                  metavar='N')
    op.add_option("--nt", dest='nt_name', default='nt',
                  help='Read values from table NAME', metavar='NAME')
                  
                  
    opts, args = op.parse_args()

    if len(args) < 1:
        msg = "Please supply a PyTables file as input."
        raise BadCommandLineError(msg, -1)

    fp = tables.openFile(args[0], 'r')

    nt = None
    for node in fp.walkNodes(classname='Table'):
        if node.name == opts.nt_name:
            nt = node

    if nt is None:
        msg = "No table with name `{0}' found in file `{1}'; aborting...".format(opts.nt_name, args[0])
        raise BadCommandLineError(msg, -2)

    if len(opts.cols) == 0:
        opts.cols = nt.colnames

    if opts.sample_size > len(nt):
        opts.sample_size = len(nt)

    if opts.range is None:
        sample_indices = numpy.random.randint(0, len(nt), opts.sample_size)
    else:
        sample_indices = slice(*opts.range)    
    
    for col in opts.cols:
        print col, nt[sample_indices][col]
        print


    fp.close()


if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
